<template>
    <a-upload
      :action="baseUrl('base/fileUpload')"
      list-type="picture-card"
      v-model:file-list="fileList as any"
      :showUploadList="showUploadList"
      @preview="handlePreview"
      @change="handleChange"
      @remove="removeImage"
    >
      <div v-if="fileList.length < props.maxLength">
        <plus-outlined />
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
</template>
<script lang="ts" setup>
import { PlusOutlined } from '@ant-design/icons-vue';
import { ref,watch } from 'vue';
import { uuid } from '@/utils/utils';
//@ts-ignore
const baseUrl = (path: string) => `${import.meta.env.VITE_APP_UPLOAD_URL as string}/uploads`;
const imageUrl =import.meta.env.VITE_APP_IMAGE_URL;
interface IShowUploadList { showPreviewIcon: boolean, showRemoveIcon: boolean }
interface IProps extends IShowUploadList {
    value:string|undefined,
    maxLength: number
}

interface FileInfo {
  file: FileItem;
  fileList: FileItem[];
}

interface FileItem {
  uid: string;
  name?: string;
  status?: string;
  response?: string;
  percent?: number;
  url?: string;
  preview?: string;
  originFileObj?: any;
  thumbUrl?:string
}

const props = withDefaults(defineProps<IProps >(),{
    maxLength: 1,
    showPreviewIcon: true,
    showRemoveIcon: true
})

const emit = defineEmits<{
  (e:"update:value",values:string):void
}>()


function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const fileList = ref<FileItem[]>([])
const previewVisible = ref<boolean>(false);
const previewImage = ref<string | undefined>('');
const showUploadList:IShowUploadList = {
    showPreviewIcon:props.showPreviewIcon,
    showRemoveIcon: props.showRemoveIcon
}


watch(()=>props.value,()=>{
  console.log("change--->",props.value)
  if(props.value!==null && props.value!==undefined){
    let list = props.value?props.value.split(","):[];
    list.forEach((url,index)=>{
      if(fileList.value[index]===undefined || fileList.value[index]===null){
        fileList.value[index] = {uid:uuid(),url,thumbUrl:url}
        
      }else{
        fileList.value[index].url = url;
        fileList.value[index].thumbUrl = url;
        console.log("修改url->",url)
      }
    })
  }
})

const handleCancel = () => {
    previewVisible.value = false
    };

    const handleChange = ({ fileList: newFileList }: FileInfo) => {
      console.log("fileList->",fileList);
      fileList.value = newFileList;
      updateValue();
    };

    const handlePreview = async (file: FileItem) => {
      if (!file.url && !file.preview) {
        file.preview = (await getBase64(file.originFileObj)) as string;
      }
      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
    };

    const removeImage = (file:FileItem)=>{
      const index = fileList.value.findIndex(fileItem=>fileItem.uid===file.uid);
      fileList.value.splice(index,1);
      updateValue();
      return Promise.resolve(true);
    }

    const updateValue = ()=>{
      let resList:string[] = fileList.value.map(fileItem=>{
      if(fileItem.status===undefined && fileItem.url)return fileItem.url;
      let response:any = fileItem.response;
      return  imageUrl+response?.key
     }).filter(url=>url!==null && url!=="");
     emit("update:value",resList.length?resList.join(","):"")
    }
</script>